<?php

namespace Anchu\Cockpit\Logics;

use Anchu\Cockpit\Decorators\Decorator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class Logic
{
    public $data;
    public $decorator;
    public $api;
    public $apiToken;
    public $url;
    public $method;

    public function __construct()
    {
        $this->data = $this->getData();
        $this->decorator = new \App\Decorators\Decorator($this->data);
    }

    public function run(Request $request)
    {
        return $this->decorator->all();
    }

    /**
     * 返回数组类型的数据
     * @return array
     */
    public function getData()
    {
        return $this->sendRequest($this->api, $this->apiToken, 'get');
    }

    /**
     * 从数仓那边获取数据
     * @param $api
     * @param $apiToken
     * @param string $method
     * @return array|mixed
     */
    public function sendRequest($api, $apiToken)
    {
        $url = $this->url . $api;
        
        if ($this->method == 'post') {
            $filter = json_decode(request()->get('filter', '{}'), 1);
            $body = ['inFields' => $filter];

            $response = Http::withHeaders(['Api-Token' => $apiToken])
                ->withBody(json_encode($body, JSON_FORCE_OBJECT), 'application/json')
                ->post($url);
        } else {
            $response = Http::withHeaders(['Api-Token' => $apiToken])
                ->get($url);
        }


        if (!$response->ok()) {
            return [];
        }
        $result = $response->json();

        if ($result['errorCode'] != 1) {
            return [];
        }

        return $result['data'];
    }
}
